﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

using Cisoft.Cisoft3G.BLL;
using Cisoft.Cisoft3G.Model;

public partial class Business_Cisoft3G_ContactsManage_ContactsManage : WebUI.Page.BasePage
{
    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindContactGroup();
            ltScript.Text = "<script type=\"text/javascript\" src=\"../../../js/Basic/BasicPage.js\"></script><script type=\"text/javascript\" src=\"../../../js/My97DatePicker/WdatePicker.js\"></script>";
            chcAll.Attributes.Add("onclick", "SelectAllCheckboxes(this)");
            Bind();
        }
    }
    #endregion 

    #region 数据绑定
    /// <summary>
    /// 数据绑定
    /// </summary>
    private void Bind()
    {
        //当前页码
        int cpn = AspNetPager1.CurrentPageIndex;
        //获取数据
        DataTable dt = new Cisoft.Cisoft3G.BLL.ContactsBO().GetListWithPage(cpn, 10, AppendString()).Tables[0];
        int pageNum = dt.Rows.Count;
        if (dt.Rows.Count > 0)
        {
            Repeater1.DataSource = dt;
            Repeater1.DataBind();
            AspNetPager1.RecordCount = new Cisoft.Cisoft3G.BLL.ContactsBO().GetListCount(cpn, 10, AppendString());
            AspNetPager1.PageSize = 10;
        }
        else
        {
            Repeater1.DataSource = dt;
            Repeater1.DataBind();
            AspNetPager1.RecordCount = new Cisoft.Cisoft3G.BLL.ContactsBO().GetListCount(cpn, 10, AppendString());
        }
    }
    #endregion

    #region 翻页事件
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        Bind();
    }
    #endregion

    #region 查询事件
    /// <summary>
    /// 查询事件
    /// </summary>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Bind();
    }
    #endregion

    #region 删除
    /// <summary>
    /// 删除事件
    /// </summary>
    protected void Button1_Click(object sender, EventArgs e)
    {
        List<int> list = new List<int>();
        foreach (RepeaterItem item in Repeater1.Items)
        {
            CheckBox cbk_single = item.FindControl("cbk_single") as CheckBox;
            if (cbk_single.Checked)
            {
                Label lblContactID = item.FindControl("lblContactID") as Label;
                if (!string.IsNullOrEmpty(lblContactID.Text))
                {
                    list.Add(int.Parse(lblContactID.Text));
                }
            }
        }

        Cisoft.Cisoft3G.BLL.ContactsBO bll = new Cisoft.Cisoft3G.BLL.ContactsBO();
        string strError = string.Empty;
        if (list.Count > 0)
        {
            try
            {
                foreach (int id in list)
                {
                    //删除管理员记录
                    ContactsMO cmo = bll.GetModel(id);
                    int uid = int.Parse(bll.GetUserAndContact(" CT_Mobile='" + cmo.CT_Mobile + "' ").Tables[0].Rows[0]["US_UserID"].ToString());
                    new Cisoft.IntegrationSystem.BLL.UserBO().Delete(uid);
                    new Cisoft.IntegrationSystem.BLL.UserInfoBO().Delete(uid);
                    //删除联系人表记录
                    bll.Delete(id);
                }
            }
            catch (Exception ex)
            {
                strError = ex.Message;
            }
            if (string.IsNullOrEmpty(strError))
            {
                //PageRight("删除成功！", "ContactsManage.aspx", "返回 ", "");
                PageRight(ModalPopupExtender1, lblTS, btnCancel, "<h4>删除成功！</h4>");
                Bind();
            }
            else
            {
                PageError(ModalPopupExtender1, lblTS, btnCancel, "删除失败，原因如下：" + strError);
                //PageError("删除失败，原因如下：" + strError + "。", Request.RawUrl);
            }
        }
    }
    #endregion 

    #region 获得查询条件
    private string AppendString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(" 1=1 ");
        //sb.Append(string.IsNullOrEmpty(txtName.Text.Trim()) ? " " : " and CT_Name like '%" + txtName.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtPhone.Text.Trim()) ? " " : " and CT_Phone like '%" + txtPhone.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtMobile.Text.Trim()) ? " " : " and CT_Mobile like '%" + txtMobile.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtEmail.Text.Trim()) ? " " : " and CT_Email like '%" + txtEmail.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtPostCode.Text.Trim()) ? " " : " and CT_PostCode like '%" + txtPostCode.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtAddress.Text.Trim()) ? " " : " and CT_Address like '%" + txtAddress.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtCompany.Text.Trim()) ? " " : " and CT_Company like '%" + txtCompany.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtCompanyAddress.Text.Trim()) ? " " : " and CT_CompanyAddress like '%" + txtCompanyAddress.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtDepartment.Text.Trim()) ? " " : " and CT_Department like '%" + txtDepartment.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtDuty.Text.Trim()) ? " " : " and CT_Duty like '%" + txtDuty.Text.Trim() + "%' ");
        //sb.Append(string.IsNullOrEmpty(txtQQ.Text.Trim()) ? " " : " and CT_QQ like '%" + txtQQ.Text.Trim() + "%' ");
        if (!string.IsNullOrEmpty(txtSearchOption.Text))
        {
            sb.Append(" and " + ddlSearchOption.SelectedValue + " like '%" + txtSearchOption.Text.Trim() + "%' ");
        }

        sb.Append(ddl_ContactGroup.SelectedValue == "0" ? " " : " and CG_ContactGroupID_FK = " + ddl_ContactGroup.SelectedValue);
        return sb.ToString();
    }

    #endregion

    #region 详细事件
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Details")
        {
            Cisoft.Cisoft3G.BLL.ContactsBO bll = new Cisoft.Cisoft3G.BLL.ContactsBO();
            Cisoft.Cisoft3G.Model.ContactsMO model = new Cisoft.Cisoft3G.Model.ContactsMO();

            model = bll.GetModel(int.Parse(e.CommandArgument.ToString()));
            if (model != null)
            {
                lblAddress.Text = model.CT_Address;
                lblCompany.Text = model.CT_Company;
                lblCompanyAddress.Text = model.CT_CompanyAddress;
                lblContactGroup.Text = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetModel(model.CG_ContactGroupID_FK).CG_GroupName;
                lblDepartment.Text = model.CT_Department;
                lblDuty.Text = model.CT_Duty;
                lblEmail.Text = model.CT_Email;
                lblMobile.Text = model.CT_Mobile;
                lblName.Text = model.CT_Name;
                lblPhone.Text = model.CT_Phone;
                lblPostCode.Text = model.CT_PostCode;
                lblQQ.Text = model.CT_QQ;

                LinkButton1_Click(source, e);       
            }
        }
        if (e.CommandName == "Edit")
        {
            int id = int.Parse(e.CommandArgument.ToString());
            LinkButton lbtnEdit = e.Item.FindControl("lbtnEdit") as LinkButton;
            Response.Redirect("ContactEdit.aspx?id=" + id.ToString()) ;
        }
        if (e.CommandName == "Upper")
        {
            string id = e.CommandArgument.ToString();
            ViewState["UpperID"] = id;

            LinkButton1_Click(source, e);
        }
    }
    #endregion

    #region 显示详细信息
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ModalPopupExtender3.Show();
    }
    
    #endregion

    #region 新增事件
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //LinkButton1_Click(sender, e);
        Response.Redirect("ContactAdd.aspx");
    }
    #endregion

    #region 绑定联系人组
    private void BindContactGroup()
    {
        Initializtion(ddl_ContactGroup, 0, 0, "全部", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
    }
    #endregion

    #region 下拉框显示树型

    /// <summary>
    /// 初始化组合框级别（无限级栏目）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    /// <param name="iParentID">父类ID</param>
    public void Initializtion(DropDownList dropList, int iDepth, int iParentID, string strTip, string id, string pid, string name, string TableName)
    {
        dropList.Items.Clear();
        dropList.Items.Add(new ListItem(strTip, "0"));

        ShowColumns(dropList, iDepth, iParentID, id, pid, name, TableName);
    }

    /// <summary>
    /// 组合框显示所有级别（无限级级别）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    ///  <param name="iParentID">父类ID</param>int iParentID
    public void ShowColumns(DropDownList dropList, int iDepth, int iParentID, string id, string pid, string name, string tableName)
    {
        //定义变量
        int iCount = 0;
        int iSum = 0;
        string strGroupName = "";
        string strGroupID = "";
        DataSet ds = new DataSet();

        ds = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetList(" " + pid + "=" + iParentID + "  order by cg_order desc");

        iCount = ds.Tables[0].Rows.Count;

        if (iCount != 0)
        {
            //iSum深度处理
            iSum = iDepth + 1;

            for (int i = 0; i < iCount; i++)
            {
                if (i == (iCount - 1))
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, strGroupID));
                }
                else
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, ds.Tables[0].Rows[i][id].ToString()));
                }
                ShowColumns(dropList, iSum, Int32.Parse(ds.Tables[0].Rows[i][id].ToString()), id, pid, name, tableName);
            }
        }
    }

    /// <summary>
    /// 字符串插入"│"字符
    /// </summary>
    /// <param name="str">需要插入"│"的字符串</param>
    /// <param name="i">插入"│"字符串的索引位置</param>
    /// <returns></returns>
    private static string GetDepth(string strGroupName, int iCount)
    {
        for (int i = 1; i < iCount; i++)
        {
            strGroupName = strGroupName.Insert(0, "│");
        }

        return strGroupName;
    }

    /// <summary>
    /// 将指定字符串里的“&nbsp;”替换为空字符
    /// </summary>
    /// <param name="strText"></param>
    /// <returns></returns>
    private string replaceWord(string strText)
    {
        string outText = strText.Replace("&nbsp;", " ");
        return outText;
    }

    #endregion

    #region 列表显示组名称
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Cisoft.Cisoft3G.BLL.ContactGroupBO bll = new Cisoft.Cisoft3G.BLL.ContactGroupBO();
        Cisoft.Cisoft3G.Model.ContactGroupMO model = new Cisoft.Cisoft3G.Model.ContactGroupMO();
        Label lblGroup;
        try
        {
            lblGroup = e.Item.FindControl("lblGroup") as Label;
            if (!string.IsNullOrEmpty(lblGroup.Text.Trim()))
            {
                model = bll.GetModel(int.Parse(lblGroup.Text.Trim()));
                if (model != null)
                {
                    lblGroup.Text = model.CG_GroupName.Length > 5 ? model.CG_GroupName.Substring(0, 3) + ".." : model.CG_GroupName;
                    lblGroup.ToolTip = model.CG_GroupName;
                }
            }
        }
        catch (Exception)
        {
        }
    }
    #endregion

    #region 导入
    protected void btnImport_Click(object sender, EventArgs e)
    {
        Response.Redirect("ContactsFromExcel.aspx");
    }
    #endregion

    #region 导出
     #region 导出筛选记录
    /// <summary>
    /// 导出筛选记录
    /// fxc 201003101115
    /// </summary>
    protected void btnExportFilter_Click(object sender, EventArgs e)
    {
        DataTable dt = CreateDateTable();

        int cpn = AspNetPager1.CurrentPageIndex;
        List<ContactsMO> modelList = new ContactsBO().GetModelList(AppendString() + " order by CT_ContactID desc");
        if (modelList.Count > 0)
        {
            foreach (ContactsMO model in modelList)
            {
                ContactGroupBO bll = new ContactGroupBO();
                ContactGroupMO cgMO = bll.GetModel(model.CG_ContactGroupID_FK);
                object[] obs = { model.CT_Name,
                                 model.CT_Sex ==1?"男":"女",
                                 model.CT_Phone,
                                 model.CT_Mobile,
                                 model.CT_Mobile2,
                                 model.CT_Email,
                                 model.CT_QQ,
                                 model.CT_Address,
                                 model.CT_PostCode,
                                 model.CT_Company,
                                 model.CT_CompanyAddress,
                                 model.CT_Department,
                                 model.CT_Duty,
                                 cgMO == null?"":cgMO.CG_GroupName
                               };
                DataRow row = dt.NewRow();
                row.ItemArray = obs;
                dt.Rows.Add(row);
            }
        }

        gvData.DataSource = dt;
        gvData.DataBind();
        ShowExcel();
    }
    #endregion

    #region 导出本页记录
    /// <summary>
    /// 导出本页记录
    /// fxc 201003101205
    /// </summary>
    protected void btnExportThisPage_Click(object sender, EventArgs e)
    {
        DataTable dt = CreateDateTable();

        int cpn = AspNetPager1.CurrentPageIndex;
        DataTable tempdt = new ContactsBO().GetListWithPage(cpn, 10, AppendString() ).Tables[0];
        if (tempdt.Rows.Count > 0)
        {
            for (int i = 0; i < tempdt.Rows.Count; i++)
            {
                ContactGroupBO bll = new ContactGroupBO();
                ContactGroupMO cgMO = bll.GetModel(int.Parse(tempdt.Rows[i]["CG_ContactGroupID_FK"].ToString()));
                object[] obs = { tempdt.Rows[i]["CT_Name"].ToString(),
                                 tempdt.Rows[i]["CT_Sex"].ToString() =="1"?"男":"女",
                                 tempdt.Rows[i]["CT_Phone"].ToString(),
                                 tempdt.Rows[i]["CT_Mobile"].ToString(),
                                 tempdt.Rows[i]["CT_Mobile2"].ToString(),
                                 tempdt.Rows[i]["CT_Email"].ToString(),
                                 tempdt.Rows[i]["CT_QQ"].ToString(),
                                 tempdt.Rows[i]["CT_Address"].ToString(),
                                 tempdt.Rows[i]["CT_PostCode"].ToString(),
                                 tempdt.Rows[i]["CT_Company"].ToString(),
                                 tempdt.Rows[i]["CT_CompanyAddress"].ToString(),
                                 tempdt.Rows[i]["CT_Department"].ToString(),
                                 tempdt.Rows[i]["CT_Duty"].ToString(),
                                 cgMO == null?"":cgMO.CG_GroupName
                               };
                DataRow row = dt.NewRow();
                row.ItemArray = obs;
                dt.Rows.Add(row);
            }
        }

        gvData.DataSource = dt;
        gvData.DataBind();
        ShowExcel();
    }
    #endregion

    #region 自定义DataTable
    /// <summary>
    /// 自定义DataTable
    /// fxc 201003101209
    /// </summary>
    /// <returns>已经绑定了数据的DataTable</returns>
    private DataTable CreateDateTable()
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("姓名"));
        dt.Columns.Add(new DataColumn("性别"));
        dt.Columns.Add(new DataColumn("电话号码"));
        dt.Columns.Add(new DataColumn("手机号码"));
        dt.Columns.Add(new DataColumn("第二手机号码"));
        dt.Columns.Add(new DataColumn("电子邮箱"));
        dt.Columns.Add(new DataColumn("QQ号码"));
        dt.Columns.Add(new DataColumn("地址"));
        dt.Columns.Add(new DataColumn("邮政编码"));
        dt.Columns.Add(new DataColumn("单位"));
        dt.Columns.Add(new DataColumn("单位地址"));
        dt.Columns.Add(new DataColumn("部门"));
        dt.Columns.Add(new DataColumn("职务"));
        dt.Columns.Add(new DataColumn("通讯录组"));

        return dt;
    }
    #endregion

    #region 导出Excel
    public void ShowExcel()
    {
        Response.Clear();
        Response.Buffer = false;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("短信接收记录", System.Text.Encoding.UTF8) + ".xls");

        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        gvData.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }
    #endregion

    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    #endregion

    #region 选择删除提示
    //显示选择删除
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(hihDelete.Value) && hihDelete.Value== "false")
        {
            lblTS.Text = "<br /><h4>请选择要删除的记录</h4><br />";
            btnConfirm2.Visible = true;
            btnCancel.Visible = false;
            ModalPopupExtender1.Show();
        }
        if (!string.IsNullOrEmpty(hihDelete.Value) && hihDelete.Value == "true")
        {
            lblTS.Text = "<br /><h4>你确认删除吗？</h4><br />";
            btnConfirm2.Visible = true;
            btnCancel.Visible = true;
            ModalPopupExtender1.Show();
        } 
    }
    protected void btnConfirm2_Click(object sender, EventArgs e)
    {
        if (hihDelete.Value == "true")
        {
            Button1_Click(sender, e);
        }
        else
        {

        }
    }
    #endregion

    #region 查看详细并发送
    protected void btnSend_Click(object sender, EventArgs e)
    {
        Response.Redirect("../AddSms.aspx?Mobile=" + lblMobile.Text);
    }
    #endregion 

    #region GridView导出Excel显示数字
    protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Row.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        }   
    }
    #endregion

    #region 提升为管理员
    //protected void btnConfirm3(object sender,EventArgs e)
    //{
    //    ContactsBO bll = new ContactsBO();
    //    ContactsMO model = new ContactsMO();
    //    model = bll.GetModel(
    //}
    #endregion
}
